from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.shortcuts import render, get_object_or_404
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from .models import ArticleColumn, ArticlePost


def article_titles(request, username=None):
    # titles = ArticlePost.objects.all()
    if username:
        user = User.objects.get(username=username)
        titles = ArticlePost.objects.filter(author=user)
        try:
            userinfo = user.userinfo
        except:
            userinfo = None
    else:
        titles = ArticlePost.objects.all()
    paginator = Paginator(titles, 10)
    page = request.GET.get('page')
    try:
        current_page = paginator.page(page)
        current_list = current_page.object_list
    except PageNotAnInteger:
        current_page = paginator.page(1)
        current_list = current_page.object_list
    except EmptyPage:
        current_page = paginator.page(paginator.num_pages)
        current_list = current_page.object_list
    if username:
        return render(request, "article/list/author_articles.html", {
        "articles": current_list, "page": current_page, "userinfo": userinfo, "user": user})
    return render(request, "article/list/article_titles.html", {
        "articles": current_list, "page": current_page})


def list_article_detail(request, id, slug):
    # article = get_object_or_404(ArticlePost, id=id, slug=slug)
    article = ArticlePost.objects.filter(id=id, slug=slug)
    return render(request, "article/list/article_detail.html", {"article": article})


@csrf_exempt
@require_POST
@login_required(login_url='/account/login/')
def like_article(request):
    article_id = request.POST.get("id")
    action = request.POST.get("action")
    if article_id and action:
        try:
            article = ArticlePost.objects.get(id=article_id)
            if action == "like":
                article.users_like.add(request.user)
                return HttpResponse("1")
            else:
                article.users_like.remove(request.user)
                return HttpResponse("2")
        except:
            return HttpResponse("no")
